package com.hnd.springframerwork.core.io;

import cn.hutool.core.lang.Assert;
import com.hnd.springframerwork.beans.BeansException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 根据 url 获取资源
 */
public class UrlResource implements Resource {
    private URL url;

    public UrlResource(URL url) {
        Assert.notNull(url);
        this.url = url;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        URLConnection con = url.openConnection();
        try {

            InputStream inputStream = con.getInputStream();
            return inputStream;
        } catch (IOException e) {
            if (con instanceof HttpURLConnection) {
                ((HttpURLConnection) con).disconnect();
            }
            throw new BeansException();
        }

    }
}
